package com.hp.interview.concurrent.threads_run_in_order;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author libo
 * 使用CyclicBarrier(回环栅栏)实现线程按顺序运行
 */
public class CyclicBarrierDemo {

    static CyclicBarrier barrier1 = new CyclicBarrier(2);
    static CyclicBarrier barrier2 = new CyclicBarrier(2);

    public static void main(String[] args) {

        final Thread thread1 = new Thread(() -> {
            try {
                System.out.println("产品经理规划新需求");
                // 等待放开栅栏1
                barrier1.await();
                System.out.println("11111111");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        final Thread thread2 = new Thread(() -> {
            try {
                System.out.println("开发人员开发新需求功能");
                // 线程2是最后达到的，栅栏1打开
                barrier1.await();
                System.out.println("2222222222");
                // 等待放开栅栏2
                barrier2.await();
                System.out.println("3333333333");

            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        final Thread thread3 = new Thread(() -> {
            try {
                System.out.println("测试人员测试新功能");
                // 线程3是最后达到的，栅栏2打开
                barrier2.await();
                System.out.println("44444444444");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        thread3.start();
        thread1.start();
        thread2.start();
    }
}